"""

    KeepNote
    Global Search extension

"""

#
#  KeepNote
#  Copyright (c) 2008-2009 Matt Rasmussen
#  Author: Matt Rasmussen <rasmus@mit.edu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# Global Search by nudels0815  (based on extension pythonprompt by matt rasmussen)
#

# python imports
import os
import shutil
import sys
import subprocess


# pygtk imports
import pygtk
pygtk.require('2.0')
import gtk
import gtk.gdk


# keepnote imports
import keepnote
from keepnote.gui import Action
from keepnote.notebook import NoteBookError


class GlobalSearch (object):
    """Global Search"""
    
    def __init__(self, main_window):
        self.main_window = main_window


    def checkSearchExistance(self,notebookpath):
        """Check if local searchengine files exist"""
    
        searchenginepath=os.path.join(notebookpath,"___Search_Engine")
        searchEngineSourcePath=os.path.join(os.path.dirname(sys.argv[0]),"extensions\Global_Search")
         
        """Check if sourcefiles exist"""
        self.checkSource(searchEngineSourcePath)
        
        """Check if searchengine dir exists - create if not"""
        if not os.path.exists(searchenginepath):
            self.main_window.set_status("create searchengine path...")
            os.mkdir(searchenginepath)
        
        """Check if searchengine exists in notebook - copy if not"""
        self.checkTarget(searchenginepath,searchEngineSourcePath)
        
        
    def checkTarget(self,searchenginepath,searchEngineSourcePath):
        FilesMissing=0
        FilesMissing+=self.checkTargetFile(searchEngineSourcePath,searchenginepath,"SIndexer.exe")
        FilesMissing+=self.checkTargetFile(searchEngineSourcePath,searchenginepath,"search_adv.js")
        FilesMissing+=self.checkTargetFile(searchEngineSourcePath,searchenginepath,"sitemap.html")
        FilesMissing+=self.checkTargetFile(searchEngineSourcePath,searchenginepath,"index.html")
        FilesMissing+=self.checkTargetFile(searchEngineSourcePath,searchenginepath,"body.html")
        FilesMissing+=self.checkTargetFile(searchEngineSourcePath,searchenginepath,"menu.html")
        FilesMissing+=self.checkTargetFile(searchEngineSourcePath,searchenginepath,"config_search.ini")
        if FilesMissing > 0:
            self.main_window.set_status("...update index...")
            subprocess.Popen(r'"' + searchenginepath + '\SIndexer.exe"')
    
    def checkFileExist(self,pathfile):
        if os.path.isfile(pathfile):
            return True
        else:
            return False

    def checkSource(self,searchEngineSourcePath):
        ErrorTxt=""
        ErrorTxt+=self.checkSourceFile(os.path.join(searchEngineSourcePath,"SIndexer.exe"))
        ErrorTxt+=self.checkSourceFile(os.path.join(searchEngineSourcePath,"search_adv.js"))
        ErrorTxt+=self.checkSourceFile(os.path.join(searchEngineSourcePath,"sitemap.html"))
        ErrorTxt+=self.checkSourceFile(os.path.join(searchEngineSourcePath,"index.html"))
        ErrorTxt+=self.checkSourceFile(os.path.join(searchEngineSourcePath,"body.html"))
        ErrorTxt+=self.checkSourceFile(os.path.join(searchEngineSourcePath,"menu.html"))
        if ErrorTxt != "" :
            self.main_window.error(ErrorTxt)
            raise NoteBookError(ErrorTxt)

    def checkSourceFile(self,FilePath):
        if not self.checkFileExist(FilePath):
            return "Error: File missing: %s \n" % FilePath
        return ""

    def checkTargetFile(self,srcPath,destPath,FileName):
        FilesMissing=0
        if not self.checkFileExist(os.path.join(destPath,FileName)):
            self.main_window.set_status("...file copy: %s" % FileName)
            shutil.copy(os.path.join(srcPath,FileName),os.path.join(destPath,FileName))
            FilesMissing=1
        return FilesMissing
            
    def show(self):
        notebook=self.main_window.get_notebook()
        notebookpath=notebook.get_path()
        self.checkSearchExistance(notebookpath)

        subprocess.Popen(r'"' + os.environ["PROGRAMFILES"] + '\Internet Explorer\IEXPLORE.EXE" '+ notebookpath +'\___Search_Engine\index.html')
    

